Arrays


Arrays in JavaScript are used to store multiple values in a single variable. They are a special type of object.

1. Creating Arrays

Arrays can be created using array literals or the Array constructor:

const arrayLiteral = [1, 2, 3, 4, 5];
const arrayConstructor = new Array(1, 2, 3, 4, 5);

2. Accessing Array Elements

Array elements can be accessed using their index:

const array = [1, 2, 3, 4, 5];
console.log(array[0]); // Outputs: 1
console.log(array[4]); // Outputs: 5

3. Modifying Array Elements

Array elements can be modified by accessing their index:

const array = [1, 2, 3, 4, 5];
array[0] = 10;
console.log(array); // Outputs: [10, 2, 3, 4, 5]

Array Methods


1. Array Creation Methods

Array()

Description: Creates an array. You can specify the length or provide elements.

Syntax: new Array([length]) or new Array(element1, element2, ...)

Example:

let arr1 = new Array(5); // Creates an empty array of length 5
        let arr2 = new Array(1, 2, 3); // Creates an array [1, 2, 3]

Array.of()

Description: Creates a new array with a variable number of arguments.

Syntax: Array.of(element1, element2, ...)

Example:

let arr = Array.of(1, 2, 3); // [1, 2, 3]

Array.from()

Description: Creates a new array from an array-like or iterable object.

Syntax: Array.from(arrayLike[, mapFn[, thisArg]])

Example:

let str = "hello";
        let arr = Array.from(str); // ['h', 'e', 'l', 'l', 'o']

2. Array Manipulation Methods

push()

Description: Adds one or more elements to the end of an array and returns the new length.

Syntax: array.push(element1, ..., elementN)

Example:

let arr = [1, 2, 3];
        arr.push(4); // [1, 2, 3, 4]

pop()

Description: Removes the last element from an array and returns that element.

Syntax: array.pop()

Example:

let arr = [1, 2, 3];
        let last = arr.pop(); // last is 3, arr is now [1, 2]

shift()

Description: Removes the first element from an array and returns that element.

Syntax: array.shift()

Example:

let arr = [1, 2, 3];
        let first = arr.shift(); // first is 1, arr is now [2, 3]

unshift()

Description: Adds one or more elements to the beginning of an array and returns the new length.

Syntax: array.unshift(element1, ..., elementN)

Example:

let arr = [2, 3];
        arr.unshift(1); // [1, 2, 3]

3. Array Iteration Methods

forEach()

Description: Executes a provided function once for each array element.

Syntax: array.forEach(callback(currentValue [, index [, array]])[, thisArg])

Example:

let arr = [1, 2, 3];
        arr.forEach(num => console.log(num)); // Logs 1, 2, 3

map()

Description: Creates a new array with the results of calling a provided function on every element in the calling array.

Syntax: array.map(callback(currentValue [, index [, array]])[, thisArg])

Example:

let arr = [1, 2, 3];
        let squared = arr.map(num => num * num); // [1, 4, 9]

filter()

Description: Creates a new array with all elements that pass the test implemented by the provided function.

Syntax: array.filter(callback(currentValue [, index [, array]])[, thisArg])

Example:

let arr = [1, 2, 3, 4];
        let evens = arr.filter(num => num % 2 === 0); // [2, 4]

reduce()

Description: Executes a reducer function on each element of the array, resulting in a single output value.

Syntax: array.reduce(callback(accumulator, currentValue[, index[, array]], initialValue)

Example:

let arr = [1, 2, 3];
        let sum = arr.reduce((acc, num) => acc + num, 0); // 6

reduceRight()

Description: Similar to reduce(), but processes elements from right to left.

Syntax: array.reduceRight(callback(accumulator, currentValue[, index[, array]], initialValue)

Example:

let arr = [1, 2, 3];
        let concatenated = arr.reduceRight((acc, num) => acc + num.toString(), ""); // "321"

4. Array Searching Methods

indexOf()

Description: Returns the first index at which a given element can be found, or -1 if it is not present.

Syntax: array.indexOf(searchElement[, fromIndex])

Example:

let arr = [1, 2, 3];
        let index = arr.indexOf(2); // 1

lastIndexOf()

Description: Returns the last index at which a given element can be found, or -1 if it is not present.

Syntax: array.lastIndexOf(searchElement[, fromIndex])

Example:

let arr = [1, 2, 3, 2];
        let index = arr
.lastIndexOf(2); // 3

find()

Description: Returns the value of the first element in the array that satisfies the provided testing function.

Syntax: array.find(callback(element[, index[, array]])[, thisArg])

Example:

let arr = [1, 2, 3];
        let found = arr.find(num => num > 1); // 2

findIndex()

Description: Returns the index of the first element in the array that satisfies the provided testing function.

Syntax: array.findIndex(callback(element[, index[, array]])[, thisArg])

Example:

let arr = [1, 2, 3];
        let index = arr.findIndex(num => num > 1); // 1

5. Array Sorting and Reversing Methods

sort()

Description: Sorts the elements of an array in place and returns the sorted array.

Syntax: array.sort([compareFunction])

Example:

let arr = [3, 1, 2];
        arr.sort(); // [1, 2, 3]

reverse()

Description: Reverses the elements of an array in place.

Syntax: array.reverse()

Example:

let arr = [1, 2, 3];
        arr.reverse(); // [3, 2, 1]

6. Array Joining and Slicing Methods

join()

Description: Joins all elements of an array into a string.

Syntax: array.join([separator])

Example:

let arr = [1, 2, 3];
        let str = arr.join('-'); // "1-2-3"

slice()

Description: Returns a shallow copy of a portion of an array into a new array object.

Syntax: array.slice([begin[, end]])

Example:

let arr = [1, 2, 3, 4];
        let newArr = arr.slice(1, 3); // [2, 3]

splice()

Description: Changes the contents of an array by removing or replacing existing elements and/or adding new elements.

Syntax: array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

Example:

let arr = [1, 2, 3, 4];
        arr.splice(1, 2, 5, 6); // arr is now [1, 5, 6, 4]

7. Array Flattening Methods

flat()

Description: Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Syntax: array.flat([depth])

Example:

let arr = [1, [2, [3]]];
        let flatArr = arr.flat(); // [1, 2, [3]]

flatMap()

Description: First maps each element using a mapping function, then flattens the result into a new array.

Syntax: array.flatMap(callback(currentValue[, index[, array]])[, thisArg])

Example:

let arr = [1, 2, 3];
        let flatMapped = arr.flatMap(num => [num, num * 2]); // [1, 2, 2, 4, 3, 6]

8. Array Testing Methods

every()

Description: Tests whether all elements in the array pass the test implemented by the provided function.

Syntax: array.every(callback(currentValue[, index[, array]])[, thisArg])

Example:

let arr = [2, 4, 6];
        let allEven = arr.every(num => num % 2 === 0); // true

some()

Description: Tests whether at least one element in the array passes the test implemented by the provided function.

Syntax: array.some(callback(currentValue[, index[, array]])[, thisArg])

Example:

let arr = [1, 2, 3];
        let hasOdd = arr.some(num => num % 2 !== 0); // true

9. Array Properties

length

Description: A property that returns the number of elements in an array.

Syntax: array.length

Example:

let arr = [1, 2, 3];
        let len = arr.length; // 3

Spread Operator with Arrays(advc.)


1. Copying Arrays

The spread operator can create a shallow copy of an array.

const originalArray = [1, 2, 3];
        const copiedArray = [...originalArray];
        
        console.log(copiedArray); // [1, 2, 3]

2. Combining Arrays

You can use the spread operator to merge multiple arrays into one.

const array1 = [1, 2, 3];
        const array2 = [4, 5, 6];
        const combinedArray = [...array1, ...array2];
        
        console.log(combinedArray); // [1, 2, 3, 4, 5, 6]

3. Adding Elements to Arrays

The spread operator can be used to add new elements when creating a new array.

const array = [2, 3];
        const newArray = [1, ...array, 4];
        
        console.log(newArray); // [1, 2, 3, 4]

4. Function Arguments

You can use the spread operator to pass elements of an array as individual arguments to a function.

const numbers = [1, 2, 3, 4];
        
        function sum(a, b, c, d) {
            return a + b + c + d;
        }
        
        const total = sum(...numbers); // 10
        console.log(total);

5. Destructuring with the Spread Operator

The spread operator can be used in destructuring assignments to capture the remaining elements in an array.

const array = [1, 2, 3, 4, 5];
        const [first, second, ...rest] = array;
        
        console.log(first); // 1
        console.log(second); // 2
        console.log(rest); // [3, 4, 5]

6. Nested Arrays

The spread operator works with nested arrays, allowing you to flatten them to some extent.

const nestedArray = [[1, 2], [3, 4]];
        const flatArray = [].concat(...nestedArray);
        
        console.log(flatArray); // [1, 2, 3, 4]

The spread operator is a versatile and concise way to work with arrays in JavaScript, whether you’re copying, combining, or manipulating them in various ways. It enhances code readability and simplifies array operations. If you have more specific scenarios in mind or further questions, feel free to ask!

Conclusion

JavaScript arrays are powerful and versatile, offering a range of methods to manipulate and work with collections of data. Each method has its specific use cases and can be combined to achieve complex data manipulations. If you have any specific questions or need further examples, feel free to ask!